package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.gather.api.domain.ErpCollectProduct;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.erp.gather.domain.ErpCollectProductOptimize;
import com.erp.gather.domain.ErpCollectProductOptimizePlan;
import com.erp.gather.domain.bo.ErpCollectProductOptimizeBo;
import com.erp.gather.domain.vo.ErpCollectProductOptimizeVo;
import com.erp.gather.mapper.ErpCollectProductExpandMapper;
import com.erp.gather.mapper.ErpCollectProductMapper;
import com.erp.gather.mapper.ErpCollectProductOptimizeMapper;
import com.erp.gather.mapper.ErpCollectProductOptimizePlanMapper;
import com.erp.gather.service.IErpCollectProductOptimizeService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 采集商品优化Service业务层处理
 *
 * @author erp
 * @date 2023-03-28
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductOptimizeServiceImpl implements IErpCollectProductOptimizeService {

    private final ErpCollectProductOptimizeMapper baseMapper;
    private final ErpCollectProductMapper erpCollectProductMapper;
    private final ErpCollectProductExpandMapper erpCollectProductExpandMapper;
    private final ErpCollectProductOptimizePlanMapper optimizePlanMapper;

    @Override
    public R<Object> processingProductsWithUpdatedImages() {
        List<String> productList = baseMapper.selectIsOptimizeList();
        for (String collectProductId : productList) {
            getOptimizePicByCollectProductId(Long.valueOf(collectProductId), 0);
            getOptimizePicByCollectProductId(Long.valueOf(collectProductId), 1);
            getOptimizePicByCollectProductId(Long.valueOf(collectProductId), 2);
            getOptimizePicByCollectProductId(Long.valueOf(collectProductId), 3);
        }
        return null;
    }


    /**
     * 查询采集商品优化
     */
    @Override
    public ErpCollectProductOptimizeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询采集商品优化列表
     */
    @Override
    public TableDataInfo<ErpCollectProductOptimizeVo> queryPageList(ErpCollectProductOptimizeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpCollectProductOptimize> lqw = buildQueryWrapper(bo);
        Page<ErpCollectProductOptimizeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<ErpCollectProductOptimize> buildQueryWrapper(ErpCollectProductOptimizeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpCollectProductOptimize> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTagIds()), ErpCollectProductOptimize::getTagIds, bo.getTagIds());
        lqw.eq(bo.getCollectProductId() != null, ErpCollectProductOptimize::getCollectProductId, bo.getCollectProductId());
        lqw.eq(StringUtils.isNotBlank(bo.getOptimizePic()), ErpCollectProductOptimize::getOptimizePic, bo.getOptimizePic());
        lqw.eq(StringUtils.isNotBlank(bo.getPics()), ErpCollectProductOptimize::getPics, bo.getPics());
        lqw.eq(bo.getType() != null, ErpCollectProductOptimize::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpCollectProductOptimize::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增采集商品优化
     */
    @Override
    public Boolean insertByBo(ErpCollectProductOptimizeBo bo) {
        ErpCollectProductOptimize add = BeanUtil.toBean(bo, ErpCollectProductOptimize.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改采集商品优化
     */
    @Override
    public Boolean updateByBo(ErpCollectProductOptimizeBo bo) {
        ErpCollectProductOptimize update = BeanUtil.toBean(bo, ErpCollectProductOptimize.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpCollectProductOptimize entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除采集商品优化
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 批量优化
     *
     * @param list
     * @return
     */
    @Override
    public R<Object> batchOptimization(List<String> list) {
        List<Long> errorId = new ArrayList<>();
        ErpCollectProduct product = new ErpCollectProduct();
        for (String id : list) {
            Long collectProductId = Long.valueOf(id);
            //获取商品
            product = erpCollectProductMapper.selectById(collectProductId);
            if (product == null) {
                errorId.add(collectProductId);
                continue;
            }
            try {
                //调用优化接口
                String imageURLs = product.getImageURLs();
                String detailImg = product.getDetailImg();
                String marketing = product.getMarketing();
                String white = product.getWhite();

                List<ErpCollectProductOptimize> optimizes = baseMapper.selectList(new LambdaQueryWrapper<ErpCollectProductOptimize>().eq(ErpCollectProductOptimize::getCollectProductId, collectProductId));

                List<ErpCollectProductOptimizePlan> optimizePlanList = new ArrayList<>();
                List<ErpCollectProductOptimize> optimizeList = new ArrayList<>();
                for (ErpCollectProductOptimize productOptimize : optimizes) {
                    String optimizePic = productOptimize.getOptimizePic();
                    String tagIds = productOptimize.getTagIds();
                    String pics = productOptimize.getPics();
                    if (imageURLs.contains(optimizePic)) {
                        if (StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(pics)) {
                            return R.fail("还有未优化的轮播图" + productOptimize.getCollectProductId());
                        }
                    } else if (detailImg.contains(optimizePic)) {
                        if (StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(pics)) {
                            return R.fail("还有未优化的详情图" + productOptimize.getCollectProductId());
                        }
                    } else if (marketing.contains(optimizePic)) {
                        if (StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(pics)) {
                            return R.fail("还有未优化的营销图" + productOptimize.getCollectProductId());
                        }
                    } else if (white.contains(optimizePic)) {
                        if (StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(pics)) {
                            return R.fail("还有未优化的白底图" + productOptimize.getCollectProductId());
                        }
                    } else {
                        // 被删除的图片
                        ErpCollectProductOptimizePlan productOptimizePlan = optimizePlanMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductOptimizePlan>()
                                .eq(ErpCollectProductOptimizePlan::getOptimizePic, optimizePic));
                        if (productOptimizePlan != null) {
                            // 任务已成功转为已作废; 其余的转为已取消
                            Integer status = productOptimizePlan.getStatus();
                            if (status == 3) {
                                productOptimizePlan.setStatus(4);
                            } else {
                                productOptimizePlan.setStatus(5);
                            }
                            optimizePlanList.add(productOptimizePlan);
                        }
                        optimizeList.add(productOptimize);
                    }
                }
                if (ObjectUtils.isNotEmpty(optimizeList)) {
                    baseMapper.deleteBatchIds(optimizeList);
                }
                if (ObjectUtils.isNotEmpty(optimizePlanList)) {
                    optimizePlanMapper.updateBatchById(optimizePlanList);
                }
                ErpCollectProductExpand erpCollectProductExpand = erpCollectProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
                erpCollectProductExpand.setIsOptimize(1);
                erpCollectProductExpandMapper.updateById(erpCollectProductExpand);
            } catch (Exception e) {
                errorId.add(collectProductId);
            }
        }
        if (errorId.size() != 0) {
            return R.fail(errorId);
        } else {
            return R.ok("已全部优化" + list.size() + "个商品");
        }
    }

    @Override
    public void copyCollectProductPic(Long oldCollectId, Long newCollectId) {
        //1、查找原商品图片
        List<ErpCollectProductOptimize> oldProductOptimizes = baseMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductOptimize>().eq(ErpCollectProductOptimize::getCollectProductId, oldCollectId)
        );
        //2、根据原商品图片，查找新商品有无该图片
        oldProductOptimizes.forEach(oldProductOptimize -> {
            ErpCollectProductOptimize newProductOptimize = baseMapper.selectOne(
                    new LambdaQueryWrapper<ErpCollectProductOptimize>()
                            .eq(ErpCollectProductOptimize::getCollectProductId, newCollectId)
                            .eq(ErpCollectProductOptimize::getOptimizePic, oldProductOptimize.getOptimizePic())
                            .eq(ErpCollectProductOptimize::getType, oldProductOptimize.getType())
            );
            if (newProductOptimize != null) {
                newProductOptimize.setPics(oldProductOptimize.getPics());
                newProductOptimize.setTagIds(oldProductOptimize.getTagIds());
                baseMapper.updateById(newProductOptimize);
            } else {
                oldProductOptimize.setCollectProductId(newCollectId);
                oldProductOptimize.setHeadUserName(null);
                oldProductOptimize.setId(null);
                baseMapper.insert(oldProductOptimize);
            }
        });
    }

    @Override
    public R<Object> makeProductNotOptimize(Long collectProductId) {
        ErpCollectProductExpand erpCollectProductExpand = erpCollectProductExpandMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getCollectProductId, collectProductId)
        );
        if (erpCollectProductExpand == null) {
            return R.fail("该商品不存在");
        }
        erpCollectProductExpand.setIsOptimize(0);
        if (erpCollectProductExpandMapper.updateById(erpCollectProductExpand) > 0) {
            return R.ok("已改为未优化");
        } else {
            return R.fail("已改为未优化");
        }    }


    @Override
    public void change() {
        List<ErpCollectProductOptimize> erpCollectProductOptimizeList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductOptimize>()
                        .eq(ErpCollectProductOptimize::getType, 3)
                        .eq(ErpCollectProductOptimize::getTagIds, 1650776561517563905L)
        );

    }

    /**
     * 查询采集商品优化列表
     */
    @Override
    public List<ErpCollectProductOptimizeVo> queryList(ErpCollectProductOptimizeBo bo) {
        LambdaQueryWrapper<ErpCollectProductOptimize> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public R<Object> addOptimizePic(List<ErpCollectProductOptimize> erpCollectProductOptimizeList, String type, String collectProductId, Integer isSave) {
        //根据id和type全部删除
        baseMapper.deleteBatchIds(erpCollectProductOptimizeList);
        //全部新增
        baseMapper.insertBatch(erpCollectProductOptimizeList);
        if (isSave == 1) { // 表示保存
            ErpCollectProduct product = erpCollectProductMapper.selectById(collectProductId);

            String imageURLs = product.getImageURLs();
            String detailImg = product.getDetailImg();
            String marketing = product.getMarketing();
            String white = product.getWhite();

            List<ErpCollectProductOptimize> optimizes = baseMapper.selectList(new LambdaQueryWrapper<ErpCollectProductOptimize>().eq(ErpCollectProductOptimize::getCollectProductId, collectProductId));

            List<ErpCollectProductOptimizePlan> optimizePlanList = new ArrayList<>();
            List<ErpCollectProductOptimizePlan> optimizePlanListDel = new ArrayList<>();
            List<ErpCollectProductOptimize> optimizeList = new ArrayList<>();
            for (ErpCollectProductOptimize productOptimize : optimizes) {
                String optimizePic = productOptimize.getOptimizePic();
                String tagIds = productOptimize.getTagIds();
                String pics = productOptimize.getPics();
                if (imageURLs.contains(optimizePic)) {
                    if (StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(pics)) {
                        return R.fail("还有未优化的轮播图");
                    }
                } else if (detailImg.contains(optimizePic)) {
                    if (StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(pics)) {
                        return R.fail("还有未优化的详情图");
                    }
                } else if (marketing.contains(optimizePic)) {
                    if (StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(pics)) {
                        return R.fail("还有未优化的营销图");
                    }
                } else if (white.contains(optimizePic)) {
                    if (StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(pics)) {
                        return R.fail("还有未优化的白底图");
                    }
                } else {
                    // 被删除的图片
                    ErpCollectProductOptimizePlan productOptimizePlan = optimizePlanMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductOptimizePlan>()
                            .eq(ErpCollectProductOptimizePlan::getOptimizePic, optimizePic));
                    if (productOptimizePlan != null) {
                        // 任务已成功转为已作废; 其余的转为已取消
                        Integer status = productOptimizePlan.getStatus();
                        if (status == 3) {
                            productOptimizePlan.setStatus(4);
                        } else {
                            productOptimizePlan.setStatus(5);
                        }
                        optimizePlanList.add(productOptimizePlan);
                    }
                    optimizeList.add(productOptimize);
                }
            }
            if (ObjectUtils.isNotEmpty(optimizeList)) {
                baseMapper.deleteBatchIds(optimizeList);
            }
            if (ObjectUtils.isNotEmpty(optimizePlanList)) {
                optimizePlanMapper.updateBatchById(optimizePlanList);
            }
            ErpCollectProductExpand erpCollectProductExpand = erpCollectProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
            erpCollectProductExpand.setIsOptimize(1);
            erpCollectProductExpandMapper.updateById(erpCollectProductExpand);
            return R.ok("已确认优化");
        }
        return R.ok("暂存成功");
    }

    @Override
    public R<Map<String, Object>> getOptimizePicByCollectProductId(Long collectProductId, Integer type) {
        Map<String, Object> map = new HashMap<>();
        //1、确认该商品是否存在
        ErpCollectProduct erpCollectProduct = erpCollectProductMapper.selectOne(new LambdaQueryWrapper<ErpCollectProduct>().eq(ErpCollectProduct::getId, collectProductId));
        if (erpCollectProduct == null) {
            map.put("returnMsg", "商品不存在");
            return R.fail(map);
        }
        //获取图集表对应表List
        //获取延伸表的对应字段List
        List<String> expandImg = new ArrayList<>();
        if (type == 1) {
            //详情
            expandImg = Arrays.asList(erpCollectProduct.getDetailImg().split(";"));
        } else if (type == 0) {
            //轮播
            expandImg = Arrays.asList(erpCollectProduct.getImageURLs().split(";"));
        } else if (type == 2) {
            //白底图
            if (erpCollectProduct.getWhite() != null) {
                expandImg.add(erpCollectProduct.getWhite());
            }
        } else if (type == 3) {
            //营销图
            if (erpCollectProduct.getMarketing() != null) {
                expandImg.add(erpCollectProduct.getMarketing());
            }
        }
        List<ErpCollectProductOptimize> erpCollectProductOptimizeList = new ArrayList<>();
        ErpCollectProductOptimize erpCollectProductOptimize = new ErpCollectProductOptimize();

        List<ErpCollectProductOptimize> erpCollectProductOptimizeSelList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductOptimize>()
                        .eq(ErpCollectProductOptimize::getCollectProductId, collectProductId)
                        .eq(ErpCollectProductOptimize::getType, type)
        );

        //处理异常订单
        if (erpCollectProductOptimizeSelList != null) {
            //当采集应有详情图数量小于现在已经有的优化图时，进行纠错
            if (expandImg.size() < erpCollectProductOptimizeSelList.size()) {
                //抽取需要优化图片为一个 新集合
                List<String> imgsList = erpCollectProductOptimizeSelList.stream()
                        .map(ErpCollectProductOptimize::getOptimizePic) // 使用方法引用提取name属性
                        .collect(Collectors.toList());
//                //删除 erpCollectProductOptimizeSelList 里多余的那张
//                List<String> finalExpandImg = expandImg;
//                List<String> nonIntersection =  imgsList.stream()
//                        .filter(e -> !finalExpandImg.contains(e))
//                        .collect(Collectors.toList());
//                System.out.println(nonIntersection);

                //找到重复的那张
                Map<String, Integer> duplicatesMap = new HashMap<>();
                for (String s : imgsList) {
                    duplicatesMap.put(s, duplicatesMap.getOrDefault(s, 0) + 1);
                }

                List<String> duplicates = duplicatesMap.entrySet().stream()
                        .filter(entry -> entry.getValue() > 1)
                        .map(Map.Entry::getKey)
                        .collect(Collectors.toList());
//                System.out.println(duplicates);

                if (duplicates.size() > 0) {
                    //删除重复的那张
                    for (String img : duplicates) {
                        ErpCollectProductOptimize optimize = baseMapper.errorNullOptimize(img, collectProductId);
                        if (ObjectUtils.isNotEmpty(optimize)) {
                            baseMapper.deleteById(optimize);
                            System.out.println("已删除重复图片：" + optimize);
                        }
                    }
                }
            }

        }


        if (expandImg.size() > 0) {
            //大于0时
            for (String img : expandImg) {
                erpCollectProductOptimize = baseMapper.getOptimizePicByCollectProductId(collectProductId, img, type);
                if (erpCollectProductOptimize == null) {
                    erpCollectProductOptimize = new ErpCollectProductOptimize();
                    erpCollectProductOptimize.setCollectProductId(collectProductId);
                    erpCollectProductOptimize.setOptimizePic(img);
                    erpCollectProductOptimize.setType(type);
                    baseMapper.insert(erpCollectProductOptimize);
                }
                erpCollectProductOptimizeList.add(erpCollectProductOptimize);
            }
        }
        map.put("picList", erpCollectProductOptimizeList);
        map.put("returnMsg", "已回显优化产品列表");
        return R.ok(map);
    }


}
